package com.supsi.segretaria.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/*
 * User: Fabio Mastromatteo
 * Date: 30.03.12 - 11.05.12
 */

/**
 * Connection TCP Server, port 9099, up to 20 client connections
 */

public class ConnectionTCP extends Thread{
    private int portNumber=9099;        // The default port
    private int maxConnections=20;      // Max connections number
    private Socket s = null;                    // Client socket
    private ServerSocket serverSocket = null;   // Server socket
    private boolean closed = false;      // server state

    public ConnectionTCP() {
    }

    /**
     * Starts the Server Socket. For every client connected, a new ConnectionThread starts.
     * All the new Threads are referenced by a ConnectionThread array.
     */
    public void run(){
        try {
        serverSocket = new ServerSocket(portNumber);   // Server socket
        ConnectionThread t[] = new ConnectionThread[maxConnections];// Connection Thread array

        System.out.println("Connection Server Started");

            while(!closed){
                s = serverSocket.accept();
                for(int i=0; i<=19; i++){
                    if(t[i]==null||t[i].closed){
                        System.out.println("New client connected");
                        (t[i] = new ConnectionThread(s)).start();
                        System.out.println("Thread crated");
                        break;
                    }
                }
            }

            serverSocket.close();
            System.out.println("ConnectionTCP Closed");

        } catch (IOException e){
            e.printStackTrace();
        }


    }

    /**
     * closes the connectionTCP
     */
    public void close() {
        closed=true;
    }
}

